﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SqlSugar ;

namespace SugarFineUI.CodeTemplates.FineUIPro.Template_ModelFirst
{
    public class FineuiList:FineuiBase
    {
        public static string GetCode(TableModel tb)
        {
            DbColumnInfo keyModel = tb.Columns.FirstOrDefault(p => p.IsPrimarykey == true) ;
            if (keyModel == null) { throw new Exception("表没有主键，没办法生成代码！FineuiList"); }

            //F('Window1').show('/AdminManager/FixCodeInfoAdd.aspx', '添加');

            string code = string.Format(@"
<%@ Page Language=""C#"" AutoEventWireup=""true"" CodeBehind=""{2}List.aspx.cs"" Inherits=""{0}.{1}{2}.List"" %>

<!DOCTYPE html>

<html>
<head runat=""server"">
    <meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"" />
    <title></title>
</head>
<body>
    <form id=""form1"" runat=""server"">
       <f:PageManager AutoSizePanelID=""Panel1"" runat=""server"" />
       <f:Panel ID=""Panel1"" runat=""server"" BodyPadding=""3px"" ShowBorder=""False"" ShowHeader=""False"" Title=""Panel"" Layout=""Fit"" AutoScroll=""True"">
            <Toolbars>
                <f:Toolbar runat=""server"">
                    <Items>
                        <f:Button ID=""Button_add"" runat=""server"" Icon=""Add"" Text=""新增"" EnablePostBack=""False"" OnClientClick=""F('Window1').show('/{4}{2}/{2}Add.aspx', '添加');"" />                      
                        <f:ToolbarSeparator runat=""server""/>
                        <f:Button ID=""Button_delete"" runat=""server"" Icon=""Delete""
                            ConfirmText=""确定要执行选中行操作吗？"" Text=""批量删除"" OnClick=""Button_delete_OnClick"" />                        
                    </Items>
                </f:Toolbar>
            </Toolbars>
            <Items>           
             <f:Grid ID=""Grid1"" runat=""server"" Title=""Grid"" AllowPaging=""True"" AllowSorting=""True"" SortDirection=""asc"" SortField=""{3}""
                    EnableCheckBoxSelect=""true"" CheckBoxSelectOnly=""True"" DataKeyNames=""{3}"" EnableTextSelection=""True"" 
                    IsDatabasePaging=""True"" ShowHeader=""False"" OnPageIndexChange=""Grid1_OnPageIndexChange"">
                    <Toolbars>
                        <f:Toolbar runat=""server"">
                            <Items>
                                <f:TextBox runat=""server"" ID=""txb_keyWord"" Label=""关键词搜索""/>
                                <f:Button ID=""btnSearch"" Text=""查询"" runat=""server"" OnClick=""btnSearch_Click"" Icon=""SystemSearch""/>
                            </Items>
                        </f:Toolbar>
                    </Toolbars>
                    <PageItems>
                        <f:ToolbarSeparator runat=""server"" />
                        <f:ToolbarText  runat=""server"" Text=""每页记录数："" />
                        <f:DropDownList runat=""server"" ID=""ddlPageSize"" Width=""80px"" AutoPostBack=""true"" OnSelectedIndexChanged=""ddlPageSize_OnSelectedIndexChanged"">
                            <f:ListItem Text=""10"" Value=""10"" />
                            <f:ListItem Text=""20"" Value=""20"" Selected=""True""/>
                            <f:ListItem Text=""50"" Value=""50"" />
                            <f:ListItem Text=""100"" Value=""100"" />
                        </f:DropDownList>
                        <f:ToolbarSeparator  runat=""server""/>          
                    </PageItems>
                    <Columns>
                        <f:WindowField TextAlign=""Center"" Icon=""Pencil"" ToolTip=""编辑"" HeaderText=""编辑""
                            WindowID=""Window1"" Title=""编辑"" DataIFrameUrlFields=""{3}"" DataIFrameUrlFormatString=""{2}Add.aspx?id={{0}}""
                            Width=""50px"" />
                        <%--查看视图View
                        <f:WindowField TextAlign=""Center"" Icon=""Information"" ToolTip=""查看详细信息"" Title=""查看详细信息"" HeaderText=""查看""
                            WindowID=""Window1"" DataIFrameUrlFields=""{3}"" DataIFrameUrlFormatString=""{2}View.aspx?id={{0}}""
                            Width=""50px"" />
                        查看视图View--%>
{5}
                   </Columns>
                </f:Grid>
            </Items>
        </f:Panel>
        
        <f:Window ID=""Window1"" runat=""server"" Height=""600px"" Width=""800px"" IsModal=""true"" EnableMaximize=""True"" EnableAjax=""True"" 
            CloseAction=""HidePostBack"" EnableIFrame=""True"" Hidden=""True"" Icon=""ApplicationFormEdit"" OnClose=""Window1_OnClose"" 
            Target=""Top"" EnableResize=""True"">
        </f:Window>
    </form>
</body>
</html>
", tb.NamespaceStr,
   GetNamespace2Str(tb.Namespace2Str),
   tb.TableName,
   keyModel.DbColumnName,
   GetNamespace2Str(tb.Namespace2Str).Replace(".","/"),
   GetGridColumnStr(tb.Columns)
   ) ;

            return code ;
        }


        /// <summary>
        /// 获取grid的列代码
        /// </summary>
        /// <param name="Items"></param>
        /// <returns></returns>
        public static string GetGridColumnStr(List<DbColumnInfo> cms)
        {
            StringBuilder sb = new StringBuilder();
            var list = cms.Where(p=>p.IsPrimarykey==false).ToList();
            
            //备用模版列代码
            sb.AppendLine("<%--<f:TemplateField runat=\"server\"  Width=\"100px\" HeaderText=\" \">");
            sb.AppendLine("       <ItemTemplate>");
            sb.AppendLine("           <%#Eval(\" \") %>");
            sb.AppendLine("       </ItemTemplate>");
            sb.AppendLine("</f:TemplateField>--%>");

            for (int i = 0; i < list.Count; i++)
            {
                switch (list[i].DataType.ToLower())
                {
                    case "system.boolean":
                        sb.AppendLine(string.Format("                        <f:CheckBoxField DataField=\"{0}\"  HeaderText=\"{1}\" RenderAsStaticField=\"true\" Width=\"50px\" />"
                            , list[i].DbColumnName, GetComment(list[i].ColumnDescription, list[i].DbColumnName)));
                        break;

                    case "system.datetime"://break;
                    case "datetime":
                        sb.AppendLine(string.Format("                        <f:BoundField runat=\"server\" DataField=\"{0}\" HeaderText=\"{1}\"  Width=\"100px\" {2}/>"
                            , list[i].DbColumnName, GetComment(list[i].ColumnDescription, list[i].DbColumnName), "DataFormatString=\"{0:yyyy-MM-dd}\""));
                        break;

                    case "system.byte"://break;
                    case "system.sbyte"://break;
                    case "system.int16"://break;
                    case "system.uint16"://break;
                        //一般来说是关联枚举值等，所以用模版列
                        sb.AppendLine(string.Format("                        <f:TemplateField runat=\"server\" Width=\"100px\" HeaderText=\"{0}\" >", GetComment(list[i].ColumnDescription , list[i].DbColumnName )));
                        sb.AppendLine("                            <ItemTemplate>");
                        sb.AppendLine(string.Format("                           <%#Eval(\"{0}\")%>", list[i].DbColumnName));
                        sb.AppendLine("                            </ItemTemplate>");
                        sb.AppendLine("                        </f:TemplateField>");
                        break;

                    case "system.int32"://break;
                    case "system.decimal"://break;
                    case "system.double"://break;
                    case "system.single":
                        //数字应该为右对齐
                        sb.AppendLine(string.Format("                        <f:BoundField runat=\"server\" DataField=\"{0}\" HeaderText=\"{1}\"  Width=\"100px\" {2}/>"
                            , list[i].DbColumnName, GetComment(list[i].ColumnDescription, list[i].DbColumnName), " TextAlign=\"Right\" "));
                        break;

                    default:
                        sb.AppendLine(string.Format("                        <f:BoundField runat=\"server\" DataField=\"{0}\" HeaderText=\"{1}\"  Width=\"100px\" />"
                            , list[i].DbColumnName, GetComment(list[i].ColumnDescription, list[i].DbColumnName)));
                        break;
                }
            }

            return sb.ToString();
        }
    }
}
